<?php
declare (strict_types = 1);

namespace app\adminapi\controller\index;

use app\common\util\ApiResponseTrait;
use think\facade\Db;

class Index
{
    use ApiResponseTrait;

    public function index()
    {
        $totalUsers = Db::name('user')->count();
        $todayNewUsers = Db::name('user')->whereDay('create_time')->count();
        $totalAdAmount = Db::name('reward_log')->sum('ecpm');
        $dailyAdAmount = Db::name('reward_log')->whereDay('create_time')->sum('ecpm');
//        publisher_revenue_cny

        // 2. 用户增长趋势：近7个月（含本月）
        $userGrowth = [];
        for ($i = 6; $i >= 0; $i--) {
            $monthStart = date('Y-m-01', strtotime("-$i months")); // 例如：2025-01-01
            $monthEnd = date('Y-m-t', strtotime("-$i months"));   // 例如：2025-01-31

            $count = Db::name('user')
                ->whereRaw("FROM_UNIXTIME(create_time, '%Y-%m-%d') BETWEEN '$monthStart' AND '$monthEnd'")
                ->count();

            $label = date('n月', strtotime($monthStart));
            $userGrowth[] = ['month' => $label, 'count' => $count];
        }

        // 3. 本周广告收入趋势（周一到周日）
        $weeklyData = [];
        $startOfWeek = strtotime('last Monday'); // 本周一
        if (date('D') === 'Mon') {
            $startOfWeek = strtotime('today'); // 今天就是周一
        } else {
            $startOfWeek = strtotime('last Monday');
        }

        for ($i = 0; $i < 7; $i++) {
            $dayStart = date('Y-m-d 00:00:00', $startOfWeek + 86400 * $i);
            $dayEnd = date('Y-m-d 23:59:59', $startOfWeek + 86400 * $i);
            $dayLabel = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][$i];

            $amount = (float) Db::name('reward_log')
                ->whereBetween('create_time', [$dayStart, $dayEnd])
                ->sum('ecpm');

            $weeklyData[] = [
                'day' => $dayLabel,
                'amount' => round($amount, 2)
            ];
        }
        return $this->success(compact('totalUsers', 'todayNewUsers', 'totalAdAmount', 'dailyAdAmount', 'userGrowth', 'weeklyData'));
    }
}